//
//  CLTabBar.swift
//  WeiBo
//
//  Created by 程雷 on 2017/1/4.
//  Copyright © 2017年 chenglei. All rights reserved.
//

import UIKit

class CLTabBar: UITabBar {

    var composeClosure: (() -> ())?
    
    //初始化方法中添加子视图
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    //不允许通过XIB,StoryBoard方式调用
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        
        addSubview(composeButton)
        
        composeButton .addTarget(self, action: #selector(clickComposeButton), for: .touchUpInside)
        
    }
    
    
   @objc private func clickComposeButton(){
    
        composeClosure?()
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()

        let w = UIScreen.main.bounds.size.width / 5
        let h = bounds.size.height
        var index = 0
        
        for subView in subviews {
            
            if subView .isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subView.frame = CGRect(x: CGFloat(index) * w, y: 0, width: w, height: h)
                
                    index += (index == 1 ? 2 : 1)
            }
            
            composeButton.center = CGPoint(x: self.center.x, y: h * 0.5)
            
            composeButton.bounds.size = CGSize(width: w, height: h)
        }
        
    }
    
    
    
    lazy var composeButton: UIButton = {
        
        let addBtn = UIButton(type: .custom)
        
        addBtn .setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        addBtn .setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        addBtn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        addBtn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
    
        addBtn .sizeToFit()
        return addBtn
    }()

}
